import java.io.*;
import java.util.*;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;

public class WeatherStore {
	static class WeatherObject {
		String woeid;
		WeatherData data;
		UrlFetchServiceWrapper rssFetch;
		UrlFetchServiceWrapper imageFetch;

		private static String YAHOO_WEATHER_RSS_URL = "http://weather.yahooapis.com/forecastrss?u=c&w=";
		
		WeatherObject(String woeid) {
			this.woeid = woeid;
			rssFetch = new UrlFetchLocalImpl(YAHOO_WEATHER_RSS_URL + woeid);
		}

		void processRssFeed() throws InvalidWoeidException {
			try {
				javax.xml.parsers.SAXParserFactory saxFactory=javax.xml.parsers.SAXParserFactory.newInstance();
				SAXParser parser=saxFactory.newSAXParser();
				YahooWeatherRSSHandler rssHandler = new YahooWeatherRSSHandler();

				parser.parse(rssFetch.getInputStream(), rssHandler);

				data = rssHandler.getWeatherData();

				//imageFetch = new UrlFetchLocalImpl(data.getImageURL());
				imageFetch = new UrlFetchServiceWrapper(data.getImageURL());
			}
			catch (InvalidWoeidException iwe) { throw iwe; }
			catch (Exception e) { e.printStackTrace(); }
		}

		void processDataStore() {
			DataStoreWrapper.storeData(woeid, data, imageFetch.getBytes());
		}

		void processImageEdit() {
			imageFetch.getInputStream();
		}


		WeatherData getData() {
			return data;
		}

		String getWoeid() {
			return woeid;
		}
	}

	public static void main(String args[]) {
		GaeAuthentication auth = null;
		try {
			auth = new GaeAuthentication();
		} catch (IOException ie) {
			ie.printStackTrace();
		}

		WoeidList woeids = new WoeidList("WOEID_Codes.txt");
		HashMap<String, WeatherObject> hash = new HashMap<String, WeatherObject>();
		Ranker topRanker = new Ranker(5, false);
		Ranker botRanker = new Ranker(5, true);
		ArrayList<String> errorList = new ArrayList<String>();

		for (String woeid : woeids) {
			WeatherObject o = new WeatherObject(woeid);
			hash.put(woeid, o);
		}

		for (WeatherObject w : hash.values()) {
			try {
				w.processRssFeed();
			} catch (InvalidWoeidException iwe) {
				errorList.add(w.getWoeid());
				continue;
			}
			topRanker.put(Integer.parseInt(w.getData().getTemperature()), w.getWoeid());
			botRanker.put(Integer.parseInt(w.getData().getTemperature()), w.getWoeid());
		}

		for (String w : errorList)
			hash.remove(w);

		for (WeatherObject w : hash.values())
			w.processDataStore();
		for (WeatherObject w : hash.values()) {
			w.processImageEdit();
		}
		for (WeatherObject w : hash.values()) {
			// sendMail
		}

		for (int temp : topRanker.keySet())
			System.out.println("Top temp : "+temp+" WOEID : " + topRanker.get(temp));
		for (int temp : botRanker.keySet())
			System.out.println("Bot temp : "+temp+" WOEID : " + botRanker.get(temp));

		auth.close();
	}
};

